﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using QLHD.Models;

namespace QLHD.Utilities
{
    public class AuthenticationHelper
    {
        private HttpRequest Request = HttpContext.Current.Request;
        private HttpResponse Response = HttpContext.Current.Response;
        private HttpSessionState Session = HttpContext.Current.Session;

        public void SetLoginCookie(string userName, string password, bool isPermanentCookie)
        {
            if (Response != null)
            {
                if (isPermanentCookie)
                {
                    FormsAuthenticationTicket userAuthTicket =
                        new FormsAuthenticationTicket(1, userName, DateTime.Now,
                        DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
                    string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
                    HttpCookie userAuthCookie = new HttpCookie
                        (FormsAuthentication.FormsCookieName, encUserAuthTicket);
                    if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
                            userAuthTicket.Expiration;
                    userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
                    Response.Cookies.Add(userAuthCookie);
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
                }
            }
        }

        public bool Authenticate(string username, string password)
        {
            username = username.ToLower();
            password = QLHD.Utilities.Utilities.Encrypt(password);
            QLHD2013Entities db = new QLHD2013Entities();
            var us = db.Users.Where(q => q.UserName == username && q.PassWord == password).FirstOrDefault();
            if (us != null)
            {
                SetupUserInfo(us);
                return true;
            }
            else
            {
                return false;
            }
            //return FormsAuthentication.Authenticate(username, password);
        }

        public List<PermissionsUser> GetUserPermissions()
        {
            if (Session["GPs"] != null && Session["phongban"] != null && Session["UserID"] != null)
            {
                return (List<PermissionsUser>)Session["GPs"];
            }
            else if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                QLHD2013Entities db = new QLHD2013Entities();
                string username = HttpContext.Current.User.Identity.Name;
                var us = db.Users.Where(q => q.UserName == username).FirstOrDefault();
                if (us != null)
                {
                    SetupUserInfo(us);

                    return us.PermissionsUsers.ToList();
                }
                else
                    return new List<PermissionsUser>();
            }
            else
                return new List<PermissionsUser>();
        }

        private void SetupUserInfo(User us)
        {
            if (us == null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                string username = HttpContext.Current.User.Identity.Name;
                QLHD2013Entities db = new QLHD2013Entities();
                us = db.Users.Where(q => q.UserName == username).FirstOrDefault();
            }
            if (us != null)
            {
                Session["UserID"] = us.ID;
                QLHD2013Entities db = new QLHD2013Entities();
                Session["GPs"] = us.PermissionsUsers.ToList();
                //danh sach phong ban ma user co quyen them hop dong
                var pbid = us.PermissionsUsers.Where(q => q.ObjectID == 1 && q.PermissionValue >= 3).Select(q => q.ItemID).ToList();
                pbid.Add(0);
                string ids = string.Join(",", pbid);
                string query = "select * from PhongBan where TrangThai=1 AND ID in (" + ids + ")";
                List<PhongBan> pbs = db.ExecuteStoreQuery<PhongBan>(query, null).ToList();
                Session["phongban"] = pbs;
                pbid = us.PermissionsUsers.Where(q => q.ObjectID == 1 && q.PermissionValue >= 1).Select(q => q.ItemID).ToList();
                pbid.Add(0);
                ids = string.Join(",", pbid);
                query = "select * from PhongBan where TrangThai=1 AND ID in (" + ids + ")";
                List<PhongBan> viewpbs = db.ExecuteStoreQuery<PhongBan>(query, null).ToList();
                Session["viewphongban"] = viewpbs;
                Session["UserID"] = us.ID;
                List<QLHD.Models.Object> obj = db.Objects.ToList();
                foreach (Models.Object objtemp in obj)
                {
                    Session[objtemp.Code] = GetUserGroupPermissions(us.ID.ToString(), objtemp.ID.ToString());
                }
            }
        }
        public int GetUserGroupPermissions(string userID, string objectID)
        {
            QLHD2013Entities db = new QLHD2013Entities();
            int reVal = 0;
            string strSQL = "SELECT MAX(PermissionValue) as PermissionValue FROM GroupPermission LEFT JOIN " +
            "GroupUser ON GroupPermission.GroupID=GroupUser.GroupID WHERE GroupPermission.ObjectID=" + objectID +
            " AND GroupUser.UserID=" + userID;
            int val = 0;
            try
            {
                val = db.ExecuteStoreQuery<int>(strSQL, null).FirstOrDefault();
            }
            catch { val = 0; }

            return val;
        }
        public List<PhongBan> GetListPhongban()
        {
            if (Session["viewonly"] != null && (bool)Session["viewonly"] == true)
            {
                if (Session["viewphongban"] != null)
                    return (List<PhongBan>)Session["viewphongban"];
                else
                {
                    new AuthenticationHelper().GetUserPermissions();
                    return (List<PhongBan>)Session["viewphongban"];
                }
            }
            else
            {
                if (Session["phongban"] != null)
                    return (List<PhongBan>)Session["phongban"];
                else
                {
                    new AuthenticationHelper().GetUserPermissions();
                    return (List<PhongBan>)Session["phongban"];
                }
            }
        }

        public int GetMemberID()
        {
            if (Session["UserID"] == null)
            {
                SetupUserInfo(null);
            }
            if (Session["UserID"] != null)
                return int.Parse(Session["UserID"].ToString());
            else
                return 0;
        }

        public static bool IsAdmin()
        {
            return HttpContext.Current.User.Identity.Name.ToLower() == "admin";
        }
    }
}